perm filename PART12.TXT[1,RWF] blob sn#540144 filedate 1980-10-07 generic text, type C, neo UTF8
COMMENT āŠ—   VALID 00003 PAGES
C REC  PAGE   DESCRIPTION
C00001 00001
C00002 00002	Sample Program
C00004 00003	Sample program
C00008 ENDMK
CāŠ—;
Sample Program

Suppose f is a continuous function, and f(0) > 0, but for sufficiently
large x, f(x) < 0.  This program will find, within .000001, a root of f(x)
= 0.

PROGRAM ROOTFIND ;

VAR     R, STEP : REAL;

BEGIN 

(* FIND FIRST INTEGER R FOR WHICH :
   F( R-1 ) > 0,  F( R ) <= 0  *)

R := 1.0 ;
WHILE F( R ) > 0.0 DO  R := R + 1 ;
STEP := 0.5 ;

WHILE  STEP > 0.000001  DO   
    BEGIN
    IF  F( R-STEP ) <= 0.0  THEN 
       R := R-STEP ;

    (* ROOT LIES BETWEEN R AND R-STEP *)
    STEP := STEP / 2.0
    END;

WRITELN ( R-STEP )
END.
Sample program

Assume f(x) is a continuous function which is negative for some range of
values of x, possibly only with x very large.  We want to find an x for
which f(x) < 0.

PROGRAM MAKENEG ;

VAR     P, X, STEP :  REAL ;

BEGIN
X := 0.0 ;
P := 1.0 ;

WHILE  F( X ) >= 0.0  DO
    BEGIN
    STEP := 1.0 / P ;
    X :=  - P + STEP / 2.0 ;
    WHILE ( F(X) >= 0.0 ) AND ( X < P ) DO
        X := X + STEP ;
    (* EITHER F(X) < 0 NOW, OR WE HAVE LOOKED
       FROM  - P TO P BY STEPS OF 1/P  *)
    P := 2.0 * P
    END;

(* NOW F(X) < 0  *)
WRITELN ( X ) 
END.

The program above will always halt; to prove it takes a series of steps.

P starts at 1, and only changes by doubling, so it is always
positive.

STEP is assigned only 1/P, so it is always positive.

In the inner iteration, x keeps getting increased by the same
positive amount  STEP;  P doesn't change.  Eventually, x must
become greater than  P, so the inner iteration eventually halts.

If the program did not halt, the outer iteration would be executed an
infinite number of times.  In the process,  P would get larger than any
given number, and  STEP would get smaller than any given number.  The
inner iteration eventually tries an x in every range of values no matter how
remote and small.  When it tries one in the range where f(x) < 0, it makes
no further change in x, and both iterations terminate.